package com.csu.geo.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.csu.geo.entity.TagUser;
import com.csu.geo.service.AdminUserService;
import com.csu.geo.service.TagLineService;
import com.csu.geo.service.TagPointService;
import com.csu.geo.service.TagPolygonService;
import com.csu.geo.service.TagUserService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@Transactional
public class TagUserController {
	private static final Logger logger=LoggerFactory.getLogger(TagUserController.class);

	@Autowired
	private TagUserService tagUserService;
	@Autowired
	private TagPolygonService tagPolygonService;
	@Autowired
	private TagPointService tagPointService;
	@Autowired
	private TagLineService tagLineService;
	@Autowired 
	private AdminUserService adminUserService;

	@RequestMapping(value = "/")
	public ModelAndView home() {

			ModelAndView view = new ModelAndView("home");
			return view;
		
	}
	@RequestMapping(value = "/home")
	public ModelAndView home2() {

			ModelAndView view = new ModelAndView("home");
			return view;
		
	}

	@RequestMapping(value = "/logout")
	public ModelAndView Logout(HttpSession session) {
		session.removeAttribute("user");
		ModelAndView view = new ModelAndView("home");
		return view;

	}

	/**
	 * 注册标报用户
	 * 
	 * @param request
	 * @param model
	 * @param userModel
	 * @param result
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/savetaguser")
	public ModelAndView saveTagUser(HttpServletRequest request, Model model,
			@Valid @ModelAttribute("userModel") TagUser userModel, BindingResult result) throws UnsupportedEncodingException {
		String userName=new String(request.getParameter("username").getBytes("iso-8859-1"), "utf-8");
		if(tagUserService.findTagUserByName(userName)!=null)
		{
			ModelAndView view =new ModelAndView("register");
			view.addObject("msg", "用户名 "+userName+" 已注册，请重新输入！");
			return view;
		}
		else {
		TagUser tagUser = new TagUser();
		// tagUser.setId(UUID.randomUUID().toString());
		tagUser.setUserName(new String(request.getParameter("username").getBytes("iso-8859-1"), "utf-8"));
		tagUser.setPassWord(new String(request.getParameter("password").getBytes("iso-8859-1"), "utf-8"));
		tagUser.setEmail(request.getParameter("email"));
		tagUser.setTel(request.getParameter("tel"));
		tagUser.setActiveStatus(1);
		tagUser.setAddress(new String(request.getParameter("address").getBytes("iso-8859-1"), "utf-8"));
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  String time=format.format(new Date());
		tagUser.setCreateTime(time);
		tagUser.setDiploma(new String(request.getParameter("diploma").getBytes("iso-8859-1"), "utf-8"));
		tagUser.setProfessional(new String(request.getParameter("professional").getBytes("iso-8859-1"), "utf-8"));
		/*
		 * 需要添加验证用户名是否存在
		 */
		String str = tagUserService.saveTagUser(tagUser);
		return new ModelAndView(str);
		}

	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value="/backAddTagUser")
	public void backAddTagUser(HttpServletResponse response,HttpServletRequest request) throws JsonParseException, JsonMappingException, IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		ObjectMapper mapper=new ObjectMapper();
		Map<String, String> map=mapper.readValue(data, Map.class); 
		TagUser tagUser=new TagUser();
		tagUser.setUserName(map.get("username"));
		tagUser.setPassWord(map.get("password"));
		tagUser.setEmail(map.get("email"));
		tagUser.setTel(map.get("tel"));
		tagUser.setActiveStatus(1);
		tagUser.setAddress(map.get("address"));
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  String time=format.format(new Date());
		tagUser.setCreateTime(time);
		tagUser.setDiploma(map.get("diploma"));
		tagUser.setProfessional(map.get("professional"));
		String userName=map.get("username");
		/*
		 * 需要添加验证用户名是否存在
		 */
		if(tagUserService.findTagUserByName(userName)!=null)
		{
			String result="{\"msg\":\"1\"}";
			response.getWriter().println(result);// 成功
		}
		else {
			 tagUserService.saveTagUser(tagUser);
			 String result="{\"msg\":\"0\"}";
				response.getWriter().println(result);// 失败
		}
	}
	@RequestMapping(value = "/login")
	public ModelAndView login_ajax() {
		ModelAndView view = new ModelAndView("login");
		return view;
	}

	@RequestMapping(value = "/loginValidate")
	public ModelAndView loginValidate(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username").trim();
		String password = request.getParameter("password").trim();
		String admin=adminUserService.backLogin(username, password);
		TagUser user = tagUserService.findTagUserByNameAndPass(username, password);
		if("0000".equals(admin))
		{
			request.getSession().setAttribute("adminuser", username);
			ModelAndView view=new ModelAndView("chome");
			return view;
			
		}else if("0002".equals(admin))
		{
			request.getSession().setAttribute("adminuser", username);
			ModelAndView view=new ModelAndView("ahome");//返回管理员分配任务页面
			return view;
		}
		else if (user != null) {
			request.getSession().setAttribute("user", user.getUserName());
			ModelAndView view=new ModelAndView("home");
			return view;
		} else {

			ModelAndView view=new ModelAndView("login");
			logger.info("----------------用户登陆失败！！------------------------------");
			view.addObject("msg", "用户名或密码错误！");
			return view;
		}

	}

	@RequestMapping(value = "/register")
	public String register() {
		return "register";
	}

	/**
	 * 根据用户名查找用户信息
	 * 
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping(value = "/getUserInfo")
	public void getUerInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String userName = session.getAttribute("user").toString();
		TagUser tagUser = tagUserService.findTagUserByName(userName);
		ObjectMapper mapper = new ObjectMapper();
		try {
			response.getWriter().println(new String(mapper.writeValueAsString(tagUser).getBytes("UTF-8"),"iso-8859-1"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/updateUserInfo")
	public void updateUserInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws IOException

	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		ObjectMapper mapper=new ObjectMapper();
         @SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		String userName = session.getAttribute("user").toString();
		String email =map.get("email");
		String tel = map.get("tel");
		String password = map.get("password");
		String address=map.get("address");
		String diploma=map.get("diploma");
		String professional=map.get("professional");
		Integer code = tagUserService.updateTagUser(email, tel, password, userName,address,diploma,professional);
		if (code == 1) {
			String result="{\"msg\":\"0\"}";
			response.getWriter().println(result);// 成功
			logger.info("------------标记员信息更新成功------------");
		} else {
			String result="{\"msg\":\"1\"}";
			response.getWriter().println(result);// 失败
			logger.info("------------标记员信息更新失败------------");
		}
	}

	@RequestMapping(value = "/getTagStatusCount")
	public void getStatusCount(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws IOException {
		String userName = session.getAttribute("user").toString();
		Integer id=tagUserService.findUserID(userName);
		Map<Integer, Integer> polygonMap = tagPolygonService.getStatusCount(id);
		Map<Integer, Integer> lineMap = tagLineService.getStatusCount(id);
		Map<Integer, Integer> pointMap = tagPointService.getStatusCount(id);
		/**
		 * 未审核总数
		 */
		int uncheck = polygonMap.get(3) + lineMap.get(3) + pointMap.get(3);
		/**
		 * 审核通过数
		 */
		int checkpass = polygonMap.get(1) + lineMap.get(1) + pointMap.get(1);
		/**
		 * 审核未通过数据
		 */
		int checkunpass = polygonMap.get(2) + lineMap.get(2) + pointMap.get(2);
		/**
		 * 标报总数
		 */
		int sum = uncheck + checkpass + checkunpass;
		Map<String, Integer> result = new HashMap<String, Integer>();
		result.put("sum", sum);
		result.put("uncheck", uncheck);
		result.put("checkpass", checkpass);
		result.put("checkunpass", checkunpass);
		ObjectMapper mapper = new ObjectMapper();
		String data=new String(mapper.writeValueAsString(result).getBytes("UTF-8"),"iso-8859-1");
		response.getWriter().println(data);
	}

	/**
	 * 获取所有标报人员接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/getAllTagUser")
	public void getAllUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<TagUser> result = tagUserService.getAllTagUser();
		ObjectMapper mapper = new ObjectMapper();
		String data=new String(mapper.writeValueAsString(result).getBytes("UTF-8"),"iso-8859-1");
		response.getWriter().println(data);
	}

	/**
	 * 获取后端统计信息
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value="/geBackStatistics")
	public void geBackStatistics(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
		Map<String, Integer> result=new HashMap<String, Integer>();
		result.put("admin", adminUserService.getAdminUserCount().intValue());
		result.put("taguser", tagUserService.getTagUserCount().intValue());
		Map<Integer, Integer> polygonMap = tagPolygonService.getStatusCount();
		Map<Integer, Integer> lineMap = tagLineService.getStatusCount();
		Map<Integer, Integer> pointMap = tagPointService.getStatusCount();
		/**
		 * 未审核总数
		 */
		int uncheck = polygonMap.get(3) + lineMap.get(3) + pointMap.get(3);
		/**
		 * 审核通过数
		 */
		Integer checkpass = polygonMap.get(1) + lineMap.get(1) + pointMap.get(1);
		/**
		 * 审核未通过数据
		 */
		Integer checkunpass = polygonMap.get(2) + lineMap.get(2) + pointMap.get(2);
		/**
		 * 标报总数
		 */
		int sum = uncheck + checkpass + checkunpass;
		result.put("sum", sum);
		double temp;
		if((checkpass+checkunpass)>0)
		{
		 temp=checkpass.doubleValue()/(checkpass.doubleValue()+checkunpass.doubleValue());
		}
		else {
			temp=0.0;
		}
		int quality= (new   Double(temp*100)).intValue();
		result.put("quality", quality);
		ObjectMapper mapper=new ObjectMapper();
		String data=mapper.writeValueAsString(result);
		 logger.info("--------------后台统计信息获取成功-------------");
		response.getWriter().println(data);		

	}
   
	/**
	 * 后台获取标报员信息 查询也可使用该接口  activeStatus{0:表示全部；1:表示启用；2；表示禁止} userame：all表示全部
	 * @param request
	 * @param response
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/backGetTagUser")
	public void backGetTagUserInfo(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data =new String(request.getParameter("data").getBytes("iso-8859-1"), "utf-8");
		
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		String userName=map.get("userName");
		Integer activeStatus=Integer.parseInt(map.get("activeStatus"));
		List<TagUser> resultList=new ArrayList<TagUser>();
		if("all".equals(userName)&&activeStatus==0)
		{
			resultList=tagUserService.getAllTagUser();
		}
		else if(userName!="all"&&activeStatus==0)
		{
			resultList=tagUserService.geTagUsersByTagUserName(userName);
		}
		else if("all".equals(userName)&&activeStatus!=0)
		{
			resultList=tagUserService.getTagUsersByActiveStatus(activeStatus);
		}
		else if(userName!="all"&&activeStatus!=0){
			resultList=tagUserService.getTagUsersByActiveStatusAndName(activeStatus, userName);
		}
		ObjectMapper mapper2=new ObjectMapper();
		String result=new String(mapper2.writeValueAsString(resultList).getBytes("UTF-8"),"iso-8859-1");
		response.getWriter().println(result);
	}
	/**
	 * 后台删除标报用户 0000:删除成功  1111:删除失败
	 * @param request
	 * @param response
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/backDeleteTagUser")
	public void backDeleteTagUser(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data=request.getParameter("data");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		Integer id=Integer.parseInt(map.get("id"));
		Integer result=tagUserService.deleteTagUser(id);
		if(result>0)
		{
		response.getWriter().println("0000");
		logger.info("---------删除用户成功----------");
		}
		else {
			logger.info("---------删除用户失败----------");
			response.getWriter().println("0001");
		}
		
	}
	/**
	 * 更新用户状态  1 启用  2  禁止
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	@RequestMapping(value="/backUpdateTagUserActiveStatus")
	public void backUpdateTagUserActiveStatus(HttpServletRequest request,HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException
	{
		String data=request.getParameter("data");
		ObjectMapper mapper=new ObjectMapper();
		@SuppressWarnings("unchecked")
		Map<String, String> map=mapper.readValue(data, Map.class);
		Integer id=Integer.parseInt(map.get("id"));
		Integer status=Integer.parseInt(map.get("status"));
		int flag=tagUserService.updateTagUserStatus(status, id);
		if(flag>0)
		{
		response.getWriter().println("0000");
		}
		else {
			response.getWriter().println("1111");
		}
	}
	
}
